package com;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 添加博客记录
 */
@WebServlet("/addUser")
public class UserServletAdd extends HttpServlet {
    DbUtil dbUtil = new DbUtil();

    public void init() throws ServletException
    {
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {

            Users users = new Users();
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            Integer sex = req.getParameter("sex") == null ? 1 : Integer.parseInt(req.getParameter("sex"));
//            Integer supper = req.getParameter("supper") == null ? 0 : Boolean.parseBoolean(req.getParameter("supper"));
            String picpath = req.getParameter("picpath");
            users.setUsername(username);
            users.setPassword(password);
            users.setSupper(0);
            users.setSex(sex);
            users.setPicpath(picpath);


            Map res = new HashMap();
            dbUtil.addUser(users);

            res.put("status",HttpServletResponse.SC_OK);//200
            res.put("msg","添加微博记录成功");

            res.put("status",303);//保存失败
            res.put("msg","添加微博记录失败");
            //响应的是json
            resp.setContentType("application/json;charset=utf-8");
            //获得对象的json格式数据
            String jsonRes =  JSON.toJSONString(res);;//gson,jaskon
            resp.getOutputStream().write(jsonRes.getBytes(StandardCharsets.UTF_8));
            resp.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void destroy()
    {
        // 什么也不做
    }
}
